﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DispatchAssist.BusinessLogical.BLL;
using DispatchAssist.BusinessLogical.Model;
using DispatchAssist.Model;
using DispatchAssist.Service;
using CarolLib.WinService;


namespace DispatchAssist.SMSSender
{
    public class Sender : IBasicTask
    {

        #region members

        static log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private  static readonly int MaxCharsNumber=1000;

        private static MessageCreateManger manger;

        private static SmsSenderServiceImplService SendService = new SmsSenderServiceImplService();

        #endregion


        #region Impletement IBasicTask
        public void Init()
        {
            manger = new MessageCreateManger();
        }

        public void Execute()
        {
            //step 1. get all send list
            List<SMSMsg> sendMsgList;
            try
            {
                sendMsgList = manger.GetUnSendSMSMsgList();

            }
            catch (Exception e)
            {
                Logger.Error("error in get send SMS List", e);
                return;
            }

            //step 2.组装发送消息
            var groups = sendMsgList.GroupBy(f => f.GroupSN);

            foreach (var items in groups)
            {
                List<SMSMsg> sendList = items.ToList();
                try
                {
                    string[] mobileNos = items.ToDictionary<SMSMsg, string>(f => f.MobileNo).Keys.ToArray();



                    if (SendMessage(mobileNos, sendList[0].MsgBody, Convert.ToInt64(items.Key)))
                    {
                        sendList.ForEach(f => f.MsgStatus = (int)Enums.MessageStatus.FinishSend);
                    }
                    else
                    {
                        sendList.ForEach(f => f.MsgStatus = (int)Enums.MessageStatus.SendError);
                    }
                }
                catch (Exception e)
                {
                    Logger.Error(e);
                    sendList.ForEach(f => f.MsgStatus = (int)Enums.MessageStatus.SendError);
                }
            }

            //step 3. 更新消息状态

            try
            {
                manger.UpdateSMSMsgStatus(sendMsgList);
            }
            catch (Exception e)
            {
                Logger.Error("error in update SMS Msg Status after Send",e);
            }

        }


        //
        public void Exit()
        {

        }

        #endregion

        #region private method

        private bool SendMessage(string[] Numbers, string messageBody, long GroupSn)
        {



            int count = messageBody.Length / MaxCharsNumber;
            int i = 0;

            while (i <= count)
            {
                try
                {
                    int startIndex = i * MaxCharsNumber;

                    int length = (startIndex + MaxCharsNumber) < messageBody.Length ? MaxCharsNumber : (messageBody.Length - startIndex);

                    string message = messageBody.Substring(startIndex, length);

                    //SendService.sendSms(1001, string.Empty, Numbers, message, 3, GroupSn);

                    SendService.sendSmsAsync(1001, string.Empty, Numbers, message, 3, GroupSn);



                    i++;
                }

                catch (System.Web.Services.Protocols.SoapException se)
                {
                    Logger.Error(string.Format(" send SMS  Webservice error, GroupSN:{0} ", GroupSn), se);
                    return false;
                }
                catch (Exception e)
                {
                    Logger.Error(string.Format(" error in Send Message, GroupSN:{0}", GroupSn), e);
                    return false;
                }

            }


            return true;
        }

        #endregion
    }
}
